import { useNavigate, useSearchParams } from 'react-router-dom'
import { InfiniteScroll, NavBar } from 'antd-mobile'

import ArticleItem from '@/component/ArticleItem'

import styles from './index.module.scss'
import { useEffect, useRef, useState } from 'react'
import { searchResponse } from '@/api/search'
import { ArticlesItem } from '@/types/data'

const Result = () => {
  const history = useNavigate()
  const params = useSearchParams()
  const query = params[0].get('q')
  // 1. 定义列表数据变量
  const [list, setList] = useState<ArticlesItem[]>([])
  // useEffect(() => {
  //   ;(async () => {
  //     const res = await searchResponse({
  //       page: count.current,
  //       per_page: 10,
  //       q: query as string,
  //     })
  //     // 赋值
  //     setList((val) => [...val, ...res.data.results])
  //   })()
  // }, [])
  const count = useRef(1)
  // 2. 控制列表加载状态：true 还有数据 | false 没有数据
  const [hasMore, setHasMore] = useState(true)
  // 3. 加载数据的方法：
  async function getSearchResponseList() {
    const res = await searchResponse({
      page: count.current,
      per_page: 10,
      q: query as string,
    })
    // 赋值
    setList((val) => [...val, ...res.data.results])
    //判断是否还有数据
    if (list.length === res.data.total_count) {
      setHasMore(false)
    } else {
      count.current = count.current + 1
    }
  }
  const renderArticleList = () => {
    return list.map((item, index) => {
      return (
        <div
          key={index}
          className="article-item"
          onClick={() => history(`/article/${1}`)}>
          <ArticleItem type={item.cover.type} item={item} />
        </div>
      )
    })
  }

  return (
    <div className={styles.root}>
      <NavBar onBack={() => history(-1)}>搜索结果</NavBar>
      <div className="article-list">
        {renderArticleList()}
        <InfiniteScroll loadMore={getSearchResponseList} hasMore={hasMore} />
      </div>
    </div>
  )
}

export default Result
